package com.zhentao.controller;

import com.zhentao.service.ChatMessageMigrationService;
import com.zhentao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 聊天管理控制器
 * 提供数据迁移、系统管理等功能
 */
@RestController
@RequestMapping("/api/chat/admin")
public class ChatAdminController {

    @Autowired
    private ChatMessageMigrationService migrationService;

    /**
     * 执行数据迁移
     */
    @PostMapping("/migrate")
    public Result<String> migrateData() {
        try {
            migrationService.migrateExistingMessages();
            return Result.success("数据迁移完成");
        } catch (Exception e) {
            return Result.fail("数据迁移失败: " + e.getMessage());
        }
    }

    /**
     * 验证迁移结果
     */
    @GetMapping("/migration-status")
    public Result<Map<String, Object>> getMigrationStatus() {
        try {
            ChatMessageMigrationService.MigrationResult result = migrationService.validateMigration();
            
            Map<String, Object> response = new HashMap<>();
            response.put("totalMessages", result.getTotalMessages());
            response.put("withConversationId", result.getWithConversationId());
            response.put("withoutConversationId", result.getWithoutConversationId());
            response.put("migrationComplete", result.isMigrationComplete());
            response.put("migrationProgress", 
                result.getTotalMessages() > 0 ? 
                    (double) result.getWithConversationId() / result.getTotalMessages() * 100 : 100.0);

            return Result.success(response);
        } catch (Exception e) {
            return Result.fail("获取迁移状态失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public Result<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "OK");
        health.put("service", "ChatMessageService");
        health.put("timestamp", System.currentTimeMillis());
        
        return Result.success(health);
    }
}